import FileToolsBar from "../FileToolsBar/FileToolsBar";
import {Box, Button, Paper, Dialog, DialogTitle, DialogContent,DialogContentText, DialogActions, TextField } from '@mui/material';
import { useState } from 'react';
import fetchData from '../../utils/ApiFetch';
import downloadFiles from '../../utils/FileDownload';
import FolderTree from '../FolderTree/FolderTree';
import CloudDownloadIcon from '@mui/icons-material/CloudDownload';

const apiUrl = process.env.REACT_APP_API_URL;
const sharePrefix = process.env.REACT_APP_SHARE_PERFIX;
const debugMode = process.env.REACT_APP_DEBUG_MODE === 'true';

function CommonToolBar(props) {
    let selectedFiles = props.selectedFiles;
    let onDone = props.onDone;
    const [openMove, setOpenMove] = useState(false);
    const [openCopy, setOpenCopy] = useState(false);
    const [openShare, setOpenShare] = useState(false);
    const [sharedCode, setSharedCode] = useState('');
    const [msg, setMsg] = useState('');
    const [shareUrl, setShareUrl] = useState('');

    const [moveSelected, setMoveSelected] = useState(null);
    const [copySelected, setCopySelected] = useState(null);
    function handleDownLoad(e) {
        console.log(selectedFiles)
        let fileName = 'downloadFile'
        if (selectedFiles.length === 1) {
            fileName = selectedFiles[0].fileName
        } else {
            fileName = 'downloadFiles.zip'
        }
        downloadFiles(selectedFiles.map((sele)=> sele.id), fileName)
    }

    function handleMove() {
        setOpenMove(true)
    }

    function handleCopy() {
        setOpenCopy(true)
    }

    function handleFilesMove(e) {
        const moveApi = async () => {
            try {
                let ids = selectedFiles.map((f)=> f.id)
                const resp = await fetchData(`${apiUrl}/file/moveTo`, 'POST', {ids: ids, destFolderId: moveSelected});
                console.log(resp);
                if (resp.code === 200) {
                    if (onDone) {
                        onDone();
                    }
                } else {
                    alert('不能移动到自己上')
                }
            } catch (error) {
                console.log(error);
            }
        }
        moveApi();
        setOpenMove(false)
    }

    function handleFilesCopy(e) {
        const copyApi = async () => {
            try {
                let ids = selectedFiles.map((f)=> f.id)
                const resp = await fetchData(`${apiUrl}/file/copyTo`, 'POST', {ids: ids, destFolderId: copySelected});
                console.log(resp);
                if (resp.code === 200) {
                    if (onDone) {
                        onDone();
                    }
                } else {
                    alert('不能复制到自己上')
                }
            } catch (error) {
                console.log(error);
            }
        }
        copyApi();
        setOpenCopy(false)
    }

    function handleDelete(e) {
        console.log(selectedFiles)
        const fileDelete = async () => {
            try {
                let ids = selectedFiles.map((f)=> f.id)
                const resp = await fetchData(`${apiUrl}/file/delete`, 'POST', {ids: ids});
                console.log(resp);
                if (onDone) {
                    onDone();
                }
            } catch (error) {
                console.log(error);
            }
        }
        fileDelete();
    }

    function handleShare() {
        const shareFile = async () => {
            try {
                let ids = selectedFiles.map((f)=> f.id)
                const resp = await fetchData(`${apiUrl}/file/share`, 'POST', {ids: ids});
                console.log(resp);
                if (resp.code === 200) {
                    setMsg('');
                    setOpenShare(true);
                    console.log(process.env)
                    setSharedCode(resp.data.sharedCode);
                    setShareUrl(window.location.protocol + "//" + window.location.host + sharePrefix + "/" + resp.data.sharedCode);
                }
                if (onDone) {
                    onDone();
                }
            } catch (error) {
                console.log(error);
            }
        }
        shareFile();
    }

    function handleShareUpdate(e) {
        const updateShared = async () => {
            try {
                const resp = await fetchData(`${apiUrl}/share/updateSharedBySharedCode`, 'POST', {sharedCode: sharedCode, msg: msg});
                console.log(resp);
                if (onDone) {
                    onDone();
                }
                setOpenShare(false);
            } catch (error) {
                console.log(error);
            }
        }
        updateShared();
    }

    const toolbar = [
        {name: '下载', params: {startIcon: <CloudDownloadIcon/>, variant:"contained", onClick:handleDownLoad}},
        {name: '分享', params: {onClick:handleShare}},
        {name: '移动', params: {onClick:handleMove}},
        {name: '复制', params: {onClick:handleCopy}},
        {name: '删除', params: {onClick:handleDelete}},
    ]
    return (
        <Box>
            <FileToolsBar toolbar={toolbar} {...props} />
            <Dialog open={openMove}>
                <DialogTitle>移动至...</DialogTitle>
                <DialogContent>
                    <DialogContentText></DialogContentText>
                    <FolderTree onSelectedChange={(folderId) => {setMoveSelected(folderId)}}/>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleFilesMove}>确定</Button>
                    <Button onClick={(e) => setOpenMove(false)}>取消</Button>
                </DialogActions>
            </Dialog>
            <Dialog open={openCopy} >
                <DialogTitle>复制至...</DialogTitle>
                <DialogContent >
                    <DialogContentText></DialogContentText>
                    <FolderTree onSelectedChange={(folderId) => {setCopySelected(folderId)}}/>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleFilesCopy}>确定</Button>
                    <Button onClick={(e) => setOpenCopy(false)}>取消</Button>
                </DialogActions>
            </Dialog>
            <Dialog open={openShare} >
                <DialogTitle>分享</DialogTitle>
                <DialogContent >
                    <DialogContentText>分享给他人即可下载文件</DialogContentText>
                    <TextField id="shared-code" label="分享地址" variant="filled" defaultValue={shareUrl} />
                    <DialogContentText>捎个话</DialogContentText>
                    <TextField id="shared-code" label="留言" variant="filled" value={msg} onChange={(e)=> setMsg(e.target.value)}/>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleShareUpdate}>确定</Button>
                    <Button onClick={(e) => setOpenShare(false)}>取消</Button>
                </DialogActions>
            </Dialog>
        </Box> 
        
    )
}

export default CommonToolBar;